const asyncHandler = require('express-async-handler');
const HealthKnowledge = require('../models/HealthKnowledge');

/**
 * @desc    获取随机健康知识
 * @route   GET /api/health-knowledge/random
 * @access  Public
 */
const getRandomHealthKnowledge = asyncHandler(async (req, res) => {
  const count = parseInt(req.query.count) || 1;
  const category = req.query.category;

  // 构建查询条件
  const query = { isPublished: true };
  if (category) {
    query.category = category;
  }

  // 获取符合条件的健康知识总数
  const totalDocs = await HealthKnowledge.countDocuments(query);
  
  // 如果没有健康知识，返回空数组
  if (totalDocs === 0) {
    return res.status(200).json([]);
  }
  
  // 随机选择健康知识
  const randomKnowledge = await HealthKnowledge.aggregate([
    { $match: query },
    { $sample: { size: Math.min(count, totalDocs) } },
    {
      $project: {
        _id: 1,
        title: 1,
        summary: 1,
        content: 1,
        category: 1,
        imageUrl: 1,
        author: 1,
        publishDate: 1,
        viewCount: 1,
        likeCount: 1,
        tags: 1
      }
    }
  ]);

  res.status(200).json(randomKnowledge);
});

/**
 * @desc    获取所有健康知识
 * @route   GET /api/health-knowledge
 * @access  Public
 */
const getAllHealthKnowledge = asyncHandler(async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const category = req.query.category;
  const tag = req.query.tag;
  const search = req.query.search;
  const isRecommended = req.query.recommended === 'true';
  
  // 构建查询条件
  const query = { isPublished: true };
  
  if (category) {
    query.category = category;
  }
  
  if (tag) {
    query.tags = tag;
  }
  
  if (isRecommended) {
    query.isRecommended = true;
  }
  
  if (search) {
    query.$or = [
      { title: { $regex: search, $options: 'i' } },
      { content: { $regex: search, $options: 'i' } },
      { summary: { $regex: search, $options: 'i' } }
    ];
  }
  
  const skip = (page - 1) * limit;
  
  // 查询并分页
  const healthKnowledge = await HealthKnowledge.find(query)
    .sort({ publishDate: -1 })
    .skip(skip)
    .limit(limit)
    .select('_id title summary content category imageUrl author publishDate viewCount likeCount tags');
  
  // 获取总数用于分页
  const total = await HealthKnowledge.countDocuments(query);
  
  res.status(200).json({
    data: healthKnowledge,
    pagination: {
      total,
      page,
      limit,
      pages: Math.ceil(total / limit)
    }
  });
});

/**
 * @desc    通过ID获取健康知识详情
 * @route   GET /api/health-knowledge/:id
 * @access  Public
 */
const getHealthKnowledgeById = asyncHandler(async (req, res) => {
  const healthKnowledge = await HealthKnowledge.findById(req.params.id);
  
  if (!healthKnowledge) {
    res.status(404);
    throw new Error('未找到健康知识');
  }
  
  // 增加浏览次数
  if (!req.query.noIncrement) {
    healthKnowledge.viewCount += 1;
    await healthKnowledge.save();
  }
  
  res.status(200).json(healthKnowledge);
});

/**
 * @desc    创建健康知识
 * @route   POST /api/health-knowledge
 * @access  Private/Admin
 */
const createHealthKnowledge = asyncHandler(async (req, res) => {
  const {
    title,
    content,
    summary,
    category,
    tags,
    imageUrl,
    author,
    source,
    isRecommended,
    isPublished
  } = req.body;
  
  // 如果没有摘要，从内容中提取前200个字符作为摘要
  const finalSummary = summary || (content && content.substring(0, 200));
  
  const healthKnowledge = await HealthKnowledge.create({
    title,
    content,
    summary: finalSummary,
    category,
    tags: tags || [],
    imageUrl,
    author,
    source,
    isRecommended: isRecommended || false,
    isPublished: isPublished !== undefined ? isPublished : true
  });
  
  if (healthKnowledge) {
    res.status(201).json(healthKnowledge);
  } else {
    res.status(400);
    throw new Error('无效的健康知识数据');
  }
});

/**
 * @desc    更新健康知识
 * @route   PUT /api/health-knowledge/:id
 * @access  Private/Admin
 */
const updateHealthKnowledge = asyncHandler(async (req, res) => {
  const healthKnowledge = await HealthKnowledge.findById(req.params.id);
  
  if (!healthKnowledge) {
    res.status(404);
    throw new Error('未找到健康知识');
  }
  
  // 更新字段
  const {
    title,
    content,
    summary,
    category,
    tags,
    imageUrl,
    author,
    source,
    isRecommended,
    isPublished
  } = req.body;
  
  healthKnowledge.title = title || healthKnowledge.title;
  healthKnowledge.content = content || healthKnowledge.content;
  
  // 如果内容更新了但摘要没有，重新生成摘要
  if (content && !summary) {
    healthKnowledge.summary = content.substring(0, 200);
  } else {
    healthKnowledge.summary = summary || healthKnowledge.summary;
  }
  
  healthKnowledge.category = category || healthKnowledge.category;
  healthKnowledge.tags = tags || healthKnowledge.tags;
  healthKnowledge.imageUrl = imageUrl || healthKnowledge.imageUrl;
  healthKnowledge.author = author || healthKnowledge.author;
  healthKnowledge.source = source || healthKnowledge.source;
  
  if (isRecommended !== undefined) {
    healthKnowledge.isRecommended = isRecommended;
  }
  
  if (isPublished !== undefined) {
    healthKnowledge.isPublished = isPublished;
  }
  
  const updatedHealthKnowledge = await healthKnowledge.save();
  res.status(200).json(updatedHealthKnowledge);
});

/**
 * @desc    删除健康知识
 * @route   DELETE /api/health-knowledge/:id
 * @access  Private/Admin
 */
const deleteHealthKnowledge = asyncHandler(async (req, res) => {
  const healthKnowledge = await HealthKnowledge.findById(req.params.id);
  
  if (!healthKnowledge) {
    res.status(404);
    throw new Error('未找到健康知识');
  }
  
  await healthKnowledge.deleteOne();
  res.status(200).json({ message: '健康知识已删除' });
});

/**
 * @desc    点赞健康知识
 * @route   PUT /api/health-knowledge/:id/like
 * @access  Public
 */
const likeHealthKnowledge = asyncHandler(async (req, res) => {
  const healthKnowledge = await HealthKnowledge.findById(req.params.id);
  
  if (!healthKnowledge) {
    res.status(404);
    throw new Error('未找到健康知识');
  }
  
  healthKnowledge.likeCount += 1;
  await healthKnowledge.save();
  
  res.status(200).json({ likeCount: healthKnowledge.likeCount });
});

module.exports = {
  getRandomHealthKnowledge,
  getAllHealthKnowledge,
  getHealthKnowledgeById,
  createHealthKnowledge,
  updateHealthKnowledge,
  deleteHealthKnowledge,
  likeHealthKnowledge
}; 